﻿namespace ThreeByte.ActiveDeck.Dashboard
{
    using System.Windows.Controls;
    using System.Windows.Navigation;
    using ActiveDeck.Dashboard.LoginUI;
    using System;

    /// <summary>
    /// <see cref="Page"/> class to present information about the current application.
    /// </summary>
    public partial class Login : Page
    {
        /// <summary>
        /// Creates a new instance of the <see cref="About"/> class.
        /// </summary>
        public Login() {
            InitializeComponent();

            this.Title = ApplicationStrings.AboutPageTitle;
        }

        private LoginRegistrationWindow _childWindow;
        private object _childWindowLock = new object();

        /// <summary>
        /// Executes when the user navigates to this page.
        /// </summary>
        protected override void OnNavigatedTo(NavigationEventArgs e) {
            if(WebContext.Current.Authentication.IsLoadingUser) {
                //During initial application load
                return;
            }

            if(WebContext.Current.User.IsAuthenticated) {
                NavigationService.Navigate(new Uri("/Home", UriKind.Relative));
                return;
            }
            
            bool register = false;

            //Open the login Window
            lock(_childWindowLock) {
                if(_childWindow != null) {
                    _childWindow.Close();
                    _childWindow = null;
                }
                _childWindow = new LoginRegistrationWindow();
                _childWindow.Show();
                if(register) {
                    _childWindow.NavigateToRegistration();
                }
            }
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e) {
            //Close the login Window, if it exists
            lock(_childWindowLock) {
                if(_childWindow != null) {
                    _childWindow.Close();
                    _childWindow = null;
                }               
            }
            base.OnNavigatedFrom(e);
        }
    }
}